package com.hframe.http.client;


import com.google.gson.JsonParser;
import com.hframe.Json.JsonToData;
import com.hframe.data.DRef;
import org.apache.log4j.Logger;

/**
 * Created by heqian on 12/6/16.
 */

public abstract class DataSuccess<T extends DRef> extends StringSuccess {
    private static Logger log = Logger.getLogger(DataSuccess.class);
    private Class<T> dataClass = null;

    public abstract void onData(T data);

    public void onParserError() {
    }

    public DataSuccess(Class<T> dataClass) {
        this.dataClass = dataClass;
    }


    @Override
    public void onString(String string) {
        try {
            DRef<?> data = this.dataClass.newInstance();
            if (JsonToData.convert(new JsonParser().parse(string), data))
                onData((T) data);
            else
                onParserError();

        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
